package dao

import (
	"common"
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
)
var UserDaoUnique *UserDao

// UserDao 持久化数据
type UserDao struct {
	pool *redis.Pool
}

func NewUserDao(pool *redis.Pool)  {
	UserDaoUnique = &UserDao{
		pool: pool,
	}
}

// findUserById 根据id查询用户
func (this *UserDao) findUserById (conn redis.Conn, userId int) (user *common.User, err error)  {
	data, err := redis.String(conn.Do("Hget", "users", userId))
	if err != nil {
		if err == redis.ErrNil {
			err = common.ERROR_NO_REGISTER
		}
		return
	}
	user = &common.User{}
	if err = json.Unmarshal([]byte(data), user); err != nil {
		fmt.Println("json.Unmarshal([]byte(data), user) err,", err)
		return
	}
	return
}


func (this *UserDao) addUserInfo(conn redis.Conn, user common.User)(err error) {
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("user json fail,err=", err)
		return
	}
	_,err = conn.Do("hset", "users", user.UserId, string(data))
	if err != nil {
		fmt.Println("add user fail")
		return
	}
	return
}

func (this *UserDao) Login (u common.User) (user *common.User, err error) {
	conn := this.pool.Get()
	defer conn.Close()

	user, err = this.findUserById(conn, u.UserId)
	if err != nil {
		return
	}

	if u.UserPwd != user.UserPwd {
		err = common.ERROR_PASSWD
	}
	return
}

func (this *UserDao) Register (u common.User) (err error) {
	conn := this.pool.Get()
	defer conn.Close()

	_, err = this.findUserById(conn, u.UserId)
	if err == nil {
		err = common.ERROR_USER_EXISTS
		return
	}
	// add userinfo
	return this.addUserInfo(conn, u)
}
